<?php

class commentsActions extends sfActions {

    public function executePost(sfWebRequest $request) {
        $model_id = $this->model_id;
        $user_id = $this->getUser()->getGuardUser()->getId();
        $dos_id = $request->getParameter('model_id', false);
        if ($dos_id === false)
            exit;
        $comment_text = $request->getParameter('comment_text', false);
        if ($comment_text === false)
            exit;

        $obj = new Comment();
        $obj->set('user_id', $user_id);
        $obj->set('dos_id', $dos_id);
        $obj->set('comment_text', $comment_text);
        $obj->save();

        $this->setLayout('iframe');
    }

    public function executeRate($request) {
        $did = $request->getParameter('did', false);
        $rate = $request->getParameter('rate', false);
        $user_id = $this->getUser()->getGuardUser()->getId();
        $rated_before = RateHistoryTable::getInstance()->rated_before('comment', $user_id, $did);
        $dos_obj = CommentTable::getInstance()->find($did);
        $current_rating = $dos_obj->getRating();
        if ($rated_before === true)
            return $this->renderText($current_rating);
        $rating_count = $dos_obj->getTimesRated();
        $new_rating = (($current_rating * $rating_count) + $rate ) / ($rating_count + 1);
        $dos_obj->setRating($new_rating);
        $dos_obj->setTimesRated($rating_count + 1);
        $dos_obj->save();
        $rh = new RateHistory();
        $rh->set('model', 'comment');
        $rh->set('user_id', $user_id);
        $rh->set('model_id', $did);
        $rh->save();
        return $this->renderText($new_rating);
        exit;
    }

}
